//
//  MyUIView.m
//  FingerDraw
//
//  Created by coolluck on 10. 1. 21..
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MyUIView.h"
#define	BrushSize	15.0
#define	BrushAlpha	0.5


@implementation MyUIView

- (id)initWithFrame:(CGRect)frame {
	if ((self = [super initWithFrame:frame])) {
		CGContextRef	context;
		CGColorSpaceRef	colorSpace;
		
		colorSpace = CGColorSpaceCreateDeviceRGB();
		_cgContext = CGBitmapContextCreate(NULL, frame.size.width, frame.size.height, 8, 4 * frame.size.width, colorSpace, kCGImageAlphaPremultipliedFirst);
		CGColorSpaceRelease(colorSpace);
		if (_cgContext == NULL) {
			[self release];
			return nil;
		}
		
		_cgLayer = CGLayerCreateWithContext(_cgContext, frame.size, NULL);
		context = CGLayerGetContext(_cgLayer);
		CGContextSetLineWidth(context, BrushSize);
		CGContextSetLineCap(context, kCGLineCapRound);
		CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
	}
    return self;
}


- (void)drawRect:(CGRect)rect {
	CGRect	bounds = [self bounds];
	CGContextRef context = UIGraphicsGetCurrentContext();
	CGImageRef	image;
	
	image = CGBitmapContextCreateImage(_cgContext);
	CGContextDrawImage(context, bounds, image);
	CGImageRelease(image);
	
	CGContextSetAlpha(context, BrushAlpha);
	CGContextDrawLayerInRect(context, bounds, _cgLayer);

}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch*	touch = [touches anyObject];
	
	if (2 <= [touch tapCount]) {
		CGContextClearRect(_cgContext, [self bounds]);
		[self setNeedsDisplay];
	}
	else {
		[self touchesMoved:touches withEvent:event];
	}

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch* touch = [touches anyObject];
	CGPoint	location = [touch locationInView:self], lastLocation = [touch previousLocationInView:self];
	CGContextRef context = CGLayerGetContext(_cgLayer);
	
	CGContextBeginPath(context);
	CGContextMoveToPoint(context, lastLocation.x, lastLocation.y);
	
	CGContextAddLineToPoint(context, location.x, location.y);
	CGContextStrokePath(context);
	
	[self setNeedsDisplay];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	CGRect bounds = [self bounds];
	CGContextSetAlpha(_cgContext, BrushAlpha);
	CGContextDrawLayerInRect(_cgContext, bounds, _cgLayer);
	
	CGContextClearRect(CGLayerGetContext(_cgLayer), bounds);
	
	[self setNeedsDisplay];
}

- (BOOL) isMultipleTouchEnabled
{
	return YES;
}


- (void)dealloc {
    [super dealloc];
	CGLayerRelease(_cgLayer);
	CGContextRelease(_cgContext);
}


@end
